#! /usr/bin/env python

import os, sys
import pygame
#import level001
from basicSprite import *
from pygame.locals import *
from helpers import *
from wizzardSprite import *
from textgameprog import *
from rotatingMenu import *
from spellSprite import *
from spellMenu import *

if not pygame.font: print 'Warning, fonts disabled'
if not pygame.mixer: print 'Warning, sound disabled'

BLOCK_SIZE = 24
clock = pygame.time.Clock()
fpslimit = 60

class PyManMain:
    """The Main PyMan Class - This class handles the main 
    initialization and creating of the Game."""
    
    """Initialization: Starts the engine, creates the window, sets
    initial values."""
    def __init__(self, width=640,height=480):
        """Initialize"""
        """Initialize PyGame"""
        pygame.init()
        """Set the window Size"""
        self.width = width
        self.height = height
        """Create the Screen"""
        self.screen = pygame.display.set_mode((self.width
                                               , self.height))

        self.sprites = pygame.sprite.RenderUpdates() # container for sprites
        self.killedSprites = pygame.sprite.RenderUpdates() # used for deleting sprites

        self.registeredForUpdates = [] # non-sprite items that should be updated

        """Create the background"""
        self.background = pygame.Surface(self.screen.get_size())
        self.background = self.background.convert_alpha()

        """Load All of our Sprites"""
        self.LoadSprites();

        self.currentWizzard = self.blueWizzard  # blueWizzard is player 1
        self.ENDTURNFLAG = "false"
        self.FIREFLAG = "false"

        """Set control focus"""
        self.focus = self.currentWizzard

    # These should probably go somewheres else eventually
    REDWIZZARD = 0
    BLUEWIZZARD = 1
    SPELL = 2

    def MainLoop(self):
        """Draw the background"""
        self.background.fill((0,0,0))

        """Draw the initial sprites"""
        self.draw(self.sprites)

        pygame.display.update() # no reclist - draws everything

        """This is the Main Loop of the Game"""
        while 1:
            for event in pygame.event.get():
                if event.type == pygame.QUIT: 
                    sys.exit()
                elif event.type == FOCUS_CHANGE:
                    if event.focus == "nextWizzard":
                        if self.ENDTURNFLAG == "false":
                            self.EndTurn() 
                    elif event.focus == "curWizzard":
                        self.focus = self.currentWizzard
                    elif event.focus == "menu":
                        sm = spellMenu(self.currentWizzard, self.screen)
                        self.sprites.add(sm.start1())
                        self.focus = sm
                        self.registeredForUpdates.append(sm) # Currently this just makes the menus be updated twice per loop (once for sprites.update() and once for each item in RegisteredFOrUpdates)
                    elif event.focus == "redWizzard":
                        self.focus = self.redWizzard
                    elif event.focus == "blueWizzard":
                        self.focus = self.blueWizzard
                    else:
                        print "Unknown focus type: " + event.focus
                elif event.type == KEYDOWN:
#                    try:
                        self.focus.MoveKeyDown(event.key)
#                        break
#                    except AttributeError as ae:
#                        print "AttributeError in KEYDOWN: ", ae, ", ", self.focus
                elif event.type == KEYUP:
#                    try:
                        self.focus.MoveKeyUp(event.key)
#                        break
#                    except AttributeError as ae:
#                        print "AttributeError in KEYUP: ", ae, ", ", self.focus
                elif event.type == WIZZARD:
                    if event.status == "damaged":
                        if self.redWizzard.hit == "OHNOES!":
                            self.redWizzard.damage()
                            self.redHealth.text = "Red Wizzard Health: %s" % self.redWizzard.health
                            self.redHealth.update()
                            self.sprites.add(self.redHealth)
                        elif self.blueWizzard.hit == "OHNOES!":
                            self.blueWizzard.damage() 
                            self.blueHealth.text = "Red Wizzard Health: %s" % self.redWizzard.health
                            self.blueHealth.update()
                            self.sprites.add(self.blueHealth)
                    elif event.status == "dead":
                        if self.redWizzard.dead == "OHNOES!":
                            #WIZZARD1 BIT THE BIGGUN
                            self.endgame.one()
                        elif self.blueWizzard.dead == "OHNOES!":
                            #WIZZARD2 BIT THE BIGGUN
                            self.endgame.two()
                        else:
                            #OHNOES ITS AN ERROR!
                            self.error()    
                elif event.type == SPELL_CAST:
                    self.sprites.add(event.spell)
     
            ## NOT SURE HOW TO UPDATE THISSUN                   
            """Update the sprites"""        
            self.sprites.update()
            
            for item in self.registeredForUpdates:
               item.update() 
              
            """Do the Drawing"""     
            self.draw(self.sprites)

    def EndTurn(self):
        self.ENDTURNFLAG == "true"
        if self.currentWizzard == self.redWizzard:
            self.currentWizzard = self.blueWizzard
        else:
            self.currentWizzard = self.redWizzard
        self.focus = self.currentWizzard
        self.ENDTURNFLAG == "false"
    
    def LoadSprites(self):
        #level1 = level001.level()
        layout = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
        img_list = self.getSprites()
        x_offset = (BLOCK_SIZE/2)
        y_offset = (BLOCK_SIZE/2)
        for y in xrange(len(layout)):
            for x in xrange(len(layout[y])):
                """Get the center point for the rects"""
                centerPoint = [(x*BLOCK_SIZE) + x_offset,
                               (y*BLOCK_SIZE) + y_offset]
                if layout[y][x] == self.REDWIZZARD + 1:
                    self.redWizzard = Wizzard(centerPoint,
                                     img_list[self.REDWIZZARD], 'red')
                    self.sprites.add(self.redWizzard)
                elif layout[y][x] == self.BLUEWIZZARD + 1:
                    self.blueWizzard = Wizzard(centerPoint,
                                     img_list[self.BLUEWIZZARD], 'blue')
                    self.sprites.add(self.blueWizzard)
        self.redHealth = basicSprite.TextSprite((0,0), "Red Wizzard Health: %s" % self.redWizzard.health, (255,0,0))
        self.redHealth.rect.midtop = (self.background.get_width()/2, 0)
        self.sprites.add(self.redHealth)
        self.blueHealth = basicSprite.TextSprite([0,0], "Blue Wizzard Health: %s" % self.blueWizzard.health, (0,0,255))
        self.blueHealth.rect.midbottom = (self.background.get_width()/2,
                self.background.get_height())
        self.sprites.add(self.blueHealth)
    
    def getSprites(self):
        """Loads the graphics files."""
        # all graphics should be in the Graphics directory
        redwizzard, rect = load_image('wizzard-stand-front-red2.png')
        bluewizzard, rect = load_image('wizzard-stand-front-blue2.png')
        spellPH, rect = load_image('bolt-PH.png')
        return [redwizzard, bluewizzard, spellPH]
    
    def draw(self, sprites, surface=False, background=False):
        """Draws the sprites.

            Only code *directly* related to drawing should
            go in here!"""
        if not surface:
            surface = self.screen
        if not background:
            background = self.background
        sprites.clear(surface, background)
        reclist = sprites.draw(surface)
        pygame.display.update(reclist)

                
                
if __name__ == "__main__":
    MainWindow = PyManMain(500,575)
    MainWindow.MainLoop()
       

